# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name： log_util
Description :
Author : 'li'
date： 2022/5/23
-------------------------------------------------
Change Activity:
2022/5/23:
-------------------------------------------------
"""
import sys

from .config import ConfigLoader
from .path import join_relative_path, create_dir, join_path


def _debug_only(record):
    return record["level"].name == "DEBUG"


def _info_only(record):
    return record["level"].name == "INFO"


def _warning_only(record):
    return record["level"].name == "WARNING"


def _error_only(record):
    return record["level"].name == "ERROR"


def _critical_only(record):
    return record["level"].name == "CRITICAL"


def refresh_logger(cfg):
    """

    Args:
        cfg:

    Returns:

    """
    from loguru import logger
    abs_log_dir = join_relative_path(cfg.directory)
    create_dir(abs_log_dir)
    logger.remove()
    if cfg.is_display_terminal:
        logger.add(sys.stdout, level=cfg.log_record_level)
    if cfg.is_write_file:
        tmp_cfg = dict(encoding='utf-8', level=cfg.log_record_level, enqueue=True, rotation=cfg.file_max_size,
                       retention=cfg.expiration_date)
        logger.add(join_path(abs_log_dir, cfg.debug_file_name), filter=_debug_only, **tmp_cfg)
        logger.add(join_path(abs_log_dir, cfg.info_file_name), filter=_info_only, **tmp_cfg)
        logger.add(join_path(abs_log_dir, cfg.warning_file_name), filter=_warning_only, **tmp_cfg)
        logger.add(join_path(abs_log_dir, cfg.error_file_name), filter=_error_only, **tmp_cfg)
        logger.add(join_path(abs_log_dir, cfg.critical_file_name), filter=_critical_only, **tmp_cfg)
    return logger


def create_default_logger():
    cfg = ConfigLoader.load_from_file(join_relative_path('config/default_config.py')).log_config
    return refresh_logger(cfg)


logger = create_default_logger()
